package com.recorder.ui.file

import android.content.Intent
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Environment
import android.support.v4.content.FileProvider
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import com.recorder.R
import kotlinx.android.synthetic.main.activity_file_list.*
import java.io.File


/**
 * Created by Administrator on 2018/9/13.
 * 文件列表的界面
 */
class FileListActivity : AppCompatActivity() {

    lateinit var fileListAdapter: FileListAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_file_list)
        mBack.setOnClickListener { finish() }

        /**
         * 设置列表适配器
         *
         */

        mRecyclerView.layoutManager = LinearLayoutManager(this)

        fileListAdapter = FileListAdapter(R.layout.item_file, arrayListOf())
        mRecyclerView.adapter = fileListAdapter
        fileListAdapter.bindToRecyclerView(mRecyclerView)
        /**
         * 读取文件列表
         */
        readFileList()

        /**
         * 列表的点击事件
         */

        fileListAdapter.setOnItemClickListener { adapter, view, position ->

            /**
             * 获取点击的条目的路径
             */
            val item = adapter.getItem(position) as File

            val path = item.path
            /**
             * 根据路径播放文件
             */

            //   startPaly(path)

            /**
             * 根据路径打开文件管理器
             */
//
//            val file = File(path)
////获取父目录
//            val parentFlie = File(file.parent)
//            val intent = Intent(Intent.ACTION_GET_CONTENT)
//
//            val uriForFile = FileProvider.getUriForFile(this, "com.recorder.fileprovider", file)
//
//            intent.setDataAndType(uriForFile, "*/*")
//            intent.addCategory(Intent.CATEGORY_OPENABLE)
//            startActivity(intent)


        }

    }


    override fun onDestroy() {
        super.onDestroy()
        if (fileListAdapter.mediaPlayer.isPlaying) {

            fileListAdapter.mediaPlayer.stop()
        }
        fileListAdapter.mediaPlayer.release()

    }

    private fun startPaly(path: String?) {
        val mediaPlayer = MediaPlayer()
        mediaPlayer.setDataSource(path)
        mediaPlayer.prepare()
        mediaPlayer.start()

    }

    private fun readFileList() {

        val specItemDir = File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/注册文件/")
        if (!specItemDir.exists()) {
            specItemDir.mkdir()
        }

        val listFiles = specItemDir.listFiles()
        //文件列表
        if (listFiles != null && listFiles.isNotEmpty()) {
            fileListAdapter.replaceData(listFiles.toList())
        }

    }


}